package com.xc.controller;


import com.xc.dto.ResultDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Api(tags = "文件上传")
public class UploadController {

    @PostMapping("/upload")
    @ApiOperation("暂时该方法每次只接收一张图片,返回的是图片地址")
    public ResultDTO add(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile != null && !multipartFile.isEmpty()) {

            /**
             * 对文件名进行操作防止文件重名
             */
            //1，获取原始文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //2,截取源文件的文件名前缀,不带后缀
            String fileNamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            //3,加工处理文件名，原文件加上时间戳
            String newFileNamePrefix = System.currentTimeMillis() + fileNamePrefix;
            //4,得到新文件名
            String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));
//            String newFileName = originalFilename;
            File file = new File("G:\\project\\xichong\\xcresourse\\out\\artifacts\\xcresourse_war_exploded/assets\\" + newFileName);
            try {
                multipartFile.transferTo(file);
                String returnPath="/assets/"+newFileName;
                return ResultDTO.builder().data(returnPath).build();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultDTO.builder().msg("error").data(null).build();
    }
}
